#include<iostream>
#include<string>
using namespace std;

#include<pthread.h>
#include<unistd.h>

const int N = 5;
int tickets = 10000;
pthread_mutex_t mutex;

void * threadRoutine(void* args)
{
    string* name = static_cast<string*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(tickets>0)
        {
            usleep(100);
            cout << *name << " sells ticket " << tickets-- << endl;
            pthread_mutex_unlock(&mutex);
            usleep(100);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    delete name;
    return nullptr;
}

int main()
{
    pthread_mutex_init(&mutex, nullptr);
    pthread_t tid[N];
    for(int i = 0; i < N; i++)
    {
        string* name = new string("thread" + to_string(i));
        pthread_create(&tid[i], nullptr, threadRoutine, name);
    }

    for(int i = 0; i < N; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}